package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.model.Order;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.repository.OrderRepository;
import com.sptpc.demo1.service.IOrderService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderService implements IOrderService {
    @Autowired
    public OrderRepository orderRepository;
    @Autowired
    public DrinkRepository drinkRepository;

    @Override
    public List<Order> getALLOrders() {
        return orderRepository.findAll();
    }

    @Override
    public void addNewOrder(Order saveorder, List<Integer> items) {
        saveorder.setState(0);//订单状态

        List<Drink> drinks = drinkRepository.findAllById(items);//下单饮品
        saveorder.setItems(drinks);

        //金额总和
        BigDecimal price = drinks.stream().map(drink -> drink.getPrice().getAmount())
                .reduce(BigDecimal.ZERO, (p1, p2) -> p1 = p1.add(p2));
        saveorder.setPrice(Money.of(CurrencyUnit.of("CNY"), price));

        orderRepository.save(saveorder);
    }

    @Override
    public List<Order> findByUserName(String username) {
        Order order = new Order();
        order.setCustomer(username);
        Example<Order> example = Example.of(order);
        return orderRepository.findAll(example);
    }

    @Override
    public List<Order> findOrder(Order order) {
        Example<Order> example=Example.of(order);
        return orderRepository.findAll(example);
    }

    @Override
    public Order setOrderState(Order order,Integer stateID) {
        order.setState(stateID);
        return orderRepository.save(order);
    }

    @Override
    public void delOrderByID(Integer id) {
        orderRepository.deleteById(id);
    }
}
